/**
 * 线程统计时间.
 * @param evt.data
 * @param evt.data.tokenId 令牌
 * @param evt.data.webAppRoot host
 * @param evt.data.yhdm 用户代码
 * @param evt.data.pfm 时间performance
 * @param evt.data.url 计算时间的url
 */
function wwnetwork(sysParams) {
	this.sysParams = sysParams;
};

wwnetwork.prototype.setParams = function(sysParams) {
	this.sysParams = sysParams;
}
/**
 * 刷新颜色状态.
 * @param index 序号
 * @param speed 速度
 */
wwnetwork.prototype.refreshState = function(index, speed, width) {
	var jsn = {
			"type":"result",
			"NetWorkTestState":index,
			"NetWorkTestSpeed":speed,
			"NetWorkTestWidth":width
	}
	return jsn;
}

/**    
 * 网速过慢    
 */
wwnetwork.prototype.bad = function(speed, width) {
	return this.refreshState(2, speed, width);	
};
/**    
 * 网速中等    
 */
wwnetwork.prototype.medium = function(speed, width) {
	return this.refreshState(1, speed, width);
};
/**    
 * 网速极佳    
 */
wwnetwork.prototype.great = function(speed, width) {
	return this.refreshState(0, speed, width);
}
/**
 * 
 */
wwnetwork.prototype.calcState = function(size, delta) {
	var speed = size * 1024/delta;
	speed = Math.round(speed * 100)/100;					
	var u = "kb/s";
	var netwidth = speed * 8/1024;
	var nu = "Mbps/s";
	netwidth = Math.round(netwidth * 100)/100;
	var re = null;
	if (speed < 64) { //delta > 121.5
		re = this.bad(speed + u, netwidth + nu);
	} else if (speed < 128) { //delta > 60.75
		re = this.medium(speed + u, netwidth + nu);
	} else {
		if(speed > 1024) {
			speed = speed/1024;
			speed = Math.round(speed * 100)/100;
			u = "Mb/s";
		}
		re = this.great(speed + u, netwidth + nu);
	}
	return re;
}
/**
 * 计算速度.
 * @param url 请求名
 */
wwnetwork.prototype.calcSpeed = function(url, callBack) {
	var performance = this.sysParams.pfm;
	if(performance != null 
			&& performance.length > 0
			   && performance[0].encodedBodySize != null) {
		var time = 0;
		var size = 0;
		if(url != null){
			for(var i = 0, ilen = performance.length; i < ilen; i++) {
				var cpfm = performance[i];
				if(cpfm.name === url) {
					time += cpfm.responseEnd - cpfm.requestStart;
					size += cpfm.encodedBodySize || 0;
				}
			}
		} else {
			/*
			 * 求所有的平均值.
			 */
			var ilen = performance.length
			if(ilen > 0) {
				for(var i = 0; i < ilen; i++) {
					var cpfm = performance[i];
					time += cpfm.responseEnd - cpfm.requestStart;
					size += cpfm.encodedBodySize || 0;
				}
				time = time/ilen;
				size = size/ilen;
			}
		}
		var re = null;
		var u = "ms";
		if(time > 200) {
			re = this.bad(time + u);
		} else if(time > 100) {
			re = this.medium(time + u);
		} else {
			re = this.great(time + u);
		}
		//测试速度
		if(size > 0) {
			re = this.calcState(size, time);
		}
		if(typeof callBack == "function") {
			callBack(re);
		}
	} else {
		//发送图片请求.
		var start = new Date().getTime();
		var _this = this;
		try {
			var size = 2.43;					
			var imgsrc = this.sysParams.webAppRoot + "/ecp/webcore/themes/default/qzz/images/yg_logo.jpg?_t="
				+ new Date().getTime();
			
			var xmlHttp = new XMLHttpRequest();	        
		    xmlHttp.open("GET", imgsrc);
		    xmlHttp.setRequestHeader("Content-Type", 
		    		"application/x-www-form-urlencoded;charset=UTF-8");				    
		    xmlHttp.send("");	        
		    xmlHttp.onreadystatechange = function() {
		    	if((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
		    		var end = new Date().getTime();
					var delta = end - start;
					var re = _this.calcState(size, delta);
					if(typeof callBack == "function") {
						callBack(re);
					}
		    	}
		    }				    
		} catch (e) {
			re = this.bad();
			if(typeof callBack == "function") {
				callBack(re);
			}
		}
	}
}
/**
 * 获取指定请求的数据信息.
 * @param url 请求网址
 */
wwnetwork.prototype.calculate = function(url, callBack) {
	this.calcSpeed(url, callBack);
}
/**
 * 发送数据包.
 */
wwnetwork.prototype.getPerformance = function() {
	 var pfm = this.sysParams.pfm || [];
	 var paramsAry = [];

	 for(var i = 0, ilen = pfm.length; i < ilen; i++) {
		 var cpfm = pfm[i];
		 var paramAry = [this.sysParams.dataType,
		                 cpfm.actionId || -1, 
		                 cpfm.ecp_uniquekey,
		                 encodeURIComponent(cpfm.name.replace(/"/g,"")),
		                 cpfm.initiatorType,
		                 cpfm.nextHopProtocal || -1,
		                 Math.round(cpfm.workerStart || -1),
		                 Math.round(cpfm.redirectStart, 10),
		                 Math.round(cpfm.redirectEnd, 10),
		                 Math.round(cpfm.fetchStart, 10),
		                 Math.round(cpfm.domainLookupStart, 10),
		                 Math.round(cpfm.domainLookupEnd, 10),
		                 Math.round(cpfm.duration, 10),
		                 Math.round(cpfm.connectStart, 10),
		                 Math.round(cpfm.connectEnd, 10),
		                 Math.round(cpfm.secureConnectionStart || 0, 10),
		                 Math.round(cpfm.requestStart, 10),
		                 Math.round(cpfm.responseStart, 10),
		                 Math.round(cpfm.responseEnd, 10),
		                 Math.round(cpfm.transferSize || -1, 10),
		                 Math.round(cpfm.encodedBodySize || -1, 10),
		                 Math.round(cpfm.decodedBodySize || -1, 10),
		                 Math.round(cpfm.uploadSize || -1, 10),
		                 Math.round(cpfm.startTime || -1, 10),
		                 cpfm.actionName || -1
		                 ]
		 var params = paramAry.join("^");
		 paramsAry.push(params);	
	 }	
	 //页面性能参数
	 var pagetiming = this.sysParams.pageTiming || {};
	 if(pagetiming && pagetiming.datatype){
		var paramAry = [
			pagetiming.datatype,			
			Math.round(pagetiming.redirectType || 0, 10),
			Math.round(pagetiming.redirectCount || 0, 10),			
			Math.round(pagetiming.unloadEventStart, 10),
			Math.round(pagetiming.unloadEventEnd, 10),
			Math.round(pagetiming.redirectStart, 10),
			Math.round(pagetiming.redirectEnd, 10),
			Math.round(pagetiming.fetchStart, 10),
			Math.round(pagetiming.domainLookupStart, 10),
			Math.round(pagetiming.domainLookupEnd, 10),
			Math.round(pagetiming.connectStart, 10),
			Math.round(pagetiming.connectEnd, 10),
			Math.round(pagetiming.secureConnectionStart || 0, 10),
			Math.round(pagetiming.requestStart, 10),
			Math.round(pagetiming.responseStart, 10),
			Math.round(pagetiming.responseEnd, 10),
			Math.round(pagetiming.domLoading, 10),
			Math.round(pagetiming.domInteractive, 10),
			Math.round(pagetiming.domContentLoadedEventStart, 10),
			Math.round(pagetiming.domContentLoadedEventEnd, 10),
			Math.round(pagetiming.domComplete, 10),
			Math.round(pagetiming.loadEventStart, 10),
			Math.round(pagetiming.loadEventEnd, 10),
			Math.round(pagetiming.asyncScriptTime, 10)
		];
		var params = paramAry.join("^");
		paramsAry.push(params);
	 }
	 
	 //操作性能数据
	 var action = this.sysParams.action;
	 if (action){
		 for(var i = 0;i < action.length;i++)
		 {
			 paramsAry.push("actionMain^" + action[i].id + "^" + action[i].id + "^" + action[i].name + "^" +action[i].duration+ "^" +action[i].ajaxTimes);
		 }
	 }
		 	 
	 //页面上下文
	 if(pfm.length || (pagetiming && pagetiming.datatype) || (action && action.length) ){		
		paramsAry = ["pageContext^" + encodeURIComponent(this.sysParams.pageUrl) + "^" + 
		this.sysParams.navigationStart+"^" + 
		this.sysParams.pageContext.sessionId + "^" + 
		this.sysParams.pageContext.userName + "^" + 
		this.sysParams.pageContext.pageId].concat(paramsAry);
		
		//todo this.sysParams.pageContext.pageId
	 }
	 return paramsAry;
}
/**
 * 请求服务端.
 * @param sysParams 参数包
 * @param syn 是否同步
 */
wwnetwork.prototype.sendService = function(sysParams, syn) {
	//var sysParams = evt.data;
	var token = sysParams.ecp_token;
	var name = sysParams.serviceName;
	var headers = sysParams.headers;
	var remoteService = sysParams.webAppRoot+"/ecp/webcore/remoteService?ecp_token="+token+"&name="+name;
    var xmlHttp = new XMLHttpRequest();	        
    xmlHttp.open("POST", remoteService, syn !== true);
    xmlHttp.setRequestHeader("Content-Type", 
    		"application/x-www-form-urlencoded;charset=UTF-8");
    if(headers != null) {
	    for(var key in headers) {
	        xmlHttp.setRequestHeader(key, headers[key]);
	    }
    }
    xmlHttp.onreadystatechange = function() {
    	if((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
    		//postMessage(xmlHttp.responseText);			
			var responseText = xmlHttp.responseText
    		if(syn !== true) {				
    		    postMessage({"type":"response","responseText":responseText});
    		}
			else if(typeof responseText == "string" && (responseText.indexOf("ajax")>=0 || responseText.indexOf("page")>=0 || responseText.indexOf("action")>=0))
			{
				localStorage && localStorage.setItem("ecp_apm_enable",responseText);
			}
    	}
    }
    xmlHttp.send(sysParams.paramData);
};

onmessage=function(evt){	    
    var sysParams = evt.data;
	/*
	 * 创建对象
	 */
	var nws = new wwnetwork(sysParams);
	if(sysParams.serviceName != null) {
		/*
		 * 往服务端发送.
		 */
		nws.sendService(sysParams);
	} else {
		/*
		 * 计算时间
		 */
		var url = sysParams.url;
		nws.calculate(url, function(jsn) {
			if(jsn != null) {
			    postMessage(jsn);
			}
		});	
		/*
		 * 发送数据包到服务端
		 */
		var paramsAry = nws.getPerformance();
			
		//发回外边.
		if(paramsAry.length > 0) {
		    postMessage({"type":"send","paramAry":paramsAry});
		}
	}
}